<?php



/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Game
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
 
abstract class Game_Plugin_Distributor_Abstract
{
  protected $_type_name = '';
  protected $_dataMap = array();
  protected $_categoryMap = array();
  protected $_config;
  
  public function __construct($config = array())
  {
    $this->loadConfig($config);
  }
  
  public function loadConfig($config)
  {
    foreach ($config as $key => $value)
    {
      $this->setConfig($key, $value);
    }
  }
  
  public function setConfig($key, $value)
  {
    $this->_config[$key] = $value;
  }
  
  
  public function getFeed($url)
  {
    $client = new Zend_Http_Client($url, array('timeout' => 30));
    $response = $client->request();
    
    return $response->getBody();
  }
  
  public function normalizeObjectData($object)
  {
    $data = array();
    foreach ($this->_dataMap as $key => $value)
    {
      $data[$value] = $object->$key;
    }
    
    return $data;
  }
  
  public function normalizeData($source)
  {
    $data = array();
    foreach ($this->_dataMap as $from_key => $to_key)
    {
      $data[$to_key] = $source[$from_key];
    }
   
    return $data;
  }  
  
  public function normalizeCategory($source)
  {
    $categories = array();
    foreach ($source as $category)
    {
      $category = trim($category);
      if (!$category) continue;
      
      if (isset($this->_categoryMap[$category]))
      {
        $categories[$category] = $this->_categoryMap[$category];  
      }
      else
      {
        $categories[$category] = Game_Model_Category::TYPE_UNCATEGORIZED;
      }
    }
    return $categories;
  }
  
  public function xml2array( $xmlObject, $out = array () )
  {
    foreach ( (array) $xmlObject as $index => $node )
      $out[$index] = ( is_object ( $node ) ) ? $this->xml2array ( $node ) : $node;
  
    return $out;
  }  
  
  public function toGame($values)
  {
    $table = Engine_Api::_()->getItemTable('game');
    $db = $table->getAdapter();
    $game = $table->createRow();
    $game->setFromArray($values);    
    
    return $game;
  }  
  
  protected function generateQuery($params = array())
  {
    $ps = array();
    foreach ($params as $key => $value)
    {
      $ps[] = $key."=".urlencode($value);
    }
    return join("&", $ps);
  }
  
  public function getFeedUrl()
  {
    $url = $this->_config['feed_url'];
    return $url;
  }
  
}